var ws;//websocket
var lock_reconnect = false;//避免重复连接
var ws_url = 'ws://' + r.websocket_ip + ':8080/cmp/vodWebSocket';

var create_ws = function (data) {
    try {
        ws = new WebSocket(ws_url);
        init_event_handler(data);
    } catch (e) {
        reconnect(ws_url);
    }
};

var ws_send = function (message) {
  ws.send(message);
};

var init_event_handler = function (data) {
    ws.onclose = function () {
        reconnect(ws_url);
    };
    ws.onerror = function () {
        reconnect(ws_url);
    };
    ws.onopen = function () {
        ws.send(data);
        //心跳检测重置
        heart_check.reset().start(data);
    };
    ws.onmessage = function (event) {
        if (event.data == 'oauth/signOut') {
            base.logout();
        }
        //如果获取到消息，心跳检测重置
        //拿到任何消息都说明当前连接是正常的
        heart_check.reset().start(data);
    };
    window.onbeforeunload = function () {
        ws.close();
    };
};

var reconnect = function (url) {
    if (lock_reconnect) return;
    lock_reconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        create_ws(url);
        lock_reconnect = false;
    }, 2000);
};

//心跳检测
var heart_check = {
    timeout: 60000,//60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function (data) {
        var self = this;
        this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            if (data) {
                ws.send(data);
            }else {
                ws.send("HeartBeat");
            }
            self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
};